package com.zahb.qadx.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

import androidx.appcompat.widget.AppCompatTextView;
import androidx.cardview.widget.CardView;
import androidx.collection.SparseArrayCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.view.StatisticsView;
import com.zahb.qadx.util.CompatHelper;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.JsonUtil;
import com.zahb.qadx.util.Tips;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class StudyStatisticsActivity extends BaseActivity {

    @BindView(R.id.tv_person_statistics)
    AppCompatTextView mTvPersonStatistics;
    @BindView(R.id.tv_date)
    AppCompatTextView mTvDate;
    @BindView(R.id.statistics_view)
    StatisticsView mStatisticsView;
    @BindView(R.id.tv_un_join_count)
    AppCompatTextView mTvUnJoinCount;
    @BindView(R.id.layout_un_join)
    CardView mLayoutUnJoin;
    @BindView(R.id.tv_join_count)
    AppCompatTextView mTvJoinCount;
    @BindView(R.id.layout_join)
    CardView mLayoutJoin;
    @BindView(R.id.tv_exam_sum)
    AppCompatTextView mTvExamSum;
    @BindView(R.id.layout_exam_sum)
    CardView mLayoutExamSum;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private BaseQuickAdapter<HashMap<String, Object>, BaseViewHolder> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int examId = getIntent().getIntExtra("examId", -1);
        examinationStatistics(examId);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_study_statistics;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);
        mTvExamSum.setText("0");
        mTvJoinCount.setText("0");
        mTvUnJoinCount.setText("0");

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new BaseQuickAdapter<HashMap<String, Object>, BaseViewHolder>(R.layout.item_list_study_statistics) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, HashMap<String, Object> map) {
                baseViewHolder.setText(R.id.tv_num, String.valueOf(baseViewHolder.getAdapterPosition() + 1))
                        .setText(R.id.tv_name, (String) map.get("userName"))
                        .setText(R.id.tv_org_name, (String) map.get("rootOrgName"))
                        .setText(R.id.tv_score, ((int) map.get("userScore")) + "分");
            }
        };
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.study_statistics;
    }

    private void examinationStatistics(int examId) {
        showProgressDialog("请稍候...");
        addDisposable(RetrofitService.getNetService()
                .examinationStatistics(examId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        JsonObject object = JsonUtil.getJsonObject(response.getData());
                        JsonElement examNum = object.get("examNum");
                        if (!examNum.isJsonNull())
                            mTvExamSum.setText(String.valueOf(examNum.getAsInt()));
                        JsonElement finishNum = object.get("finishNum");
                        if (!finishNum.isJsonNull())
                            mTvJoinCount.setText(String.valueOf(finishNum.getAsInt()));
                        JsonElement unfinishNum = object.get("unfinishNum");
                        if (!unfinishNum.isJsonNull())
                            mTvUnJoinCount.setText(String.valueOf(unfinishNum.getAsInt()));
                        mStatisticsView.setNum(Integer.parseInt(CompatHelper.getString(mTvJoinCount)),
                                Integer.parseInt(CompatHelper.getString(mTvUnJoinCount)));
                        examinationList(examId);
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void examinationList(int examId) {
        showProgressDialog("请稍候...");
        Map<String, Object> params = new TreeMap<>();
        params.put("startPage", 1);
        params.put("pageSize", 8);
        params.put("examId", examId);
        addDisposable(RetrofitService.getNetService()
                .examinationList(JsonUtil.getRequestBody(params))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        if (response.getData().getTotal() > 0) {
                            List<Object> objects = response.getData().getList();
                            List<HashMap<String, Object>> userInfoMapList = new ArrayList<>();
                            for (int i = 0; i < objects.size(); i++) {
                                JsonObject object = JsonUtil.getJsonObject(objects.get(i));
                                HashMap<String, Object> map = new HashMap<>();
                                map.put("rootOrgId", object.get("rootOrgId").getAsInt());
                                map.put("userScore", object.get("userScore").getAsInt());
                                JsonObject users = object.getAsJsonObject("users");
                                map.put("userName", users.get("userName").getAsString());
                                userInfoMapList.add(map);
                            }
                            getOrganizeList(userInfoMapList);
                        } else {
                            ViewGroup parent = (ViewGroup) mRecyclerView.getParent();
                            parent.setVisibility(View.GONE);
                        }
                    } else {
                        if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                            showBindToast(response.getErrorInfo());
                        }
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void getOrganizeList(List<HashMap<String, Object>> userInfoMapList) {
        showProgressDialog("请稍候...");
        Map<String, Object> params = new TreeMap<>();
        params.put("functionsId", 185);
        params.put("orgType", 0);
        addDisposable(RetrofitService.getNetService()
                .getOrganizeList(JsonUtil.getRequestBody(params))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        List<Object> objects = response.getData();
                        SparseArrayCompat<String> arrayCompat = new SparseArrayCompat<>();
                        for (int i = 0; i < objects.size(); i++) {
                            JsonObject object = JsonUtil.getJsonObject(objects.get(i));
                            int id = object.get("id").getAsInt();
                            String name = object.get("name").getAsString();
                            arrayCompat.put(id, name);
                        }
                        for (int i = 0; i < userInfoMapList.size(); i++) {
                            HashMap<String, Object> map = userInfoMapList.get(i);
                            int rootOrgId = (int) map.get("rootOrgId");
                            String rootOrgName = arrayCompat.get(rootOrgId);
                            map.put("rootOrgName", rootOrgName);
                        }
                        mAdapter.setList(userInfoMapList);
                    } else if (response.getStatusCode() != Constant.CODE_OFFLINE) {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
}
